package site.qjdb.controller;


import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import site.qjdb.constant.Info;
import site.qjdb.pojo.*;
import site.qjdb.pojo.response.CommonResult;
import site.qjdb.pojo.response.ResponseCode;
import site.qjdb.service.*;
import site.qjdb.util.CommonUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {
	@Resource
	private OrderService orderService;
	@Resource
	private UserService userService;
	@Resource
	private GoodsService goodsService;
	@Resource
	private CartService cartService;

	/**
	 * 	从购物车添加订单
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/addByCart", method = RequestMethod.POST)
	public Object addByCart(@RequestParam String param,
			HttpServletRequest request,
			HttpSession session,
			HttpServletResponse response) {
		// 处理session和Cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if (i == 0) {
			return new CommonResult<>(ResponseCode.UNLOGIN);
		}
		// 判断用户个人信息是否完整
		User userSession = (User)session.getAttribute(Info.USER_SESSION);
		if("".equals(userSession.getNickname()) || 
				"".equals(userSession.getPhoneNumber()) || "".equals(userSession.getDepartment())) {
			return new CommonResult<>(ResponseCode.INCOMPLETE_USER_INFO);
		}
		try {
			String[] params = param.split("\\$");
			Integer dbTotal = new Integer("0");
			List<OrderItem> orderItemList = new ArrayList<>();
			List<Cart> cartList = new ArrayList<>();
			List<Goods> goodsList = new ArrayList<>();
			List<Integer> notMeList = new ArrayList<>(); // 商品卖家List
			for (String p : params) {
				String gid = p.split("#")[0];
				String cartId = p.split("#")[1];
				Integer gidInteger = Integer.parseInt(gid);
				Integer cartIdInteger = Integer.parseInt(cartId);
				// 根据gid查找Goods，查看有没有下架
				Goods _goods = new Goods();
				_goods.setState(1);
				_goods.setGid(gidInteger);
				Goods newGoods = goodsService.findGoods(_goods);
				if (newGoods == null) {
					throw new Exception();
				}
				// 不能预约自己发布的商品
				if(newGoods.getUser().getUid() == ((User)session.getAttribute(Info.USER_SESSION)).getUid()) {
					return new CommonResult<>(ResponseCode.ORDER_OWN_GOODS);
				}
				// 添加商品卖家
				notMeList.add(newGoods.getUser().getUid());
				// 查找Cart，获得count，subtotal
				Cart _cart = new Cart();
				// 设置uid
				_cart.setUid(((User)session.getAttribute(Info.USER_SESSION)).getUid());
				// 设置cartId
				_cart.setCartId(cartIdInteger);
				// 设置gid
				Goods goods = new Goods();
				goods.setGid(gidInteger);
				_cart.setGoods(goods);
				// 设置未删除
				_cart.setIsDel(0);
				List<Cart> _cartList = cartService.findCartAll(_cart);
				if(_cartList == null) {
					throw new Exception();
				}
				// 添加购物车项
				// 设置删除
				_cart.setIsDel(1);
				cartList.add(_cart);
				// 获得购物车项
				Cart newCart = _cartList.get(0);
				// 设置订单子项
				OrderItem orderItem = new OrderItem();
				// 设置购买的商品数量
				orderItem.setCount(newCart.getCount());
				// 设置订单小计
				Integer dbSubtotal = newCart.getDbSubtotal();
				// 累加计算订单总额
				dbTotal = dbTotal + dbSubtotal;
				orderItem.setDbSubtotal(dbSubtotal);
				// 设置订单子项对应的商品
				orderItem.setGoods(goods);
				// 设置订单子项状态
				orderItem.setState(0);
				// 订单子项未设置oid
				orderItemList.add(orderItem);
				// 商品预约数增加
				Integer reservedCount = newGoods.getReservedCount();
				Integer cartCount = newCart.getCount();
				if(reservedCount + cartCount > newGoods.getCount()) {
					throw new Exception();
				}
				if(reservedCount + cartCount == newGoods.getCount()) {
					// 商品已全部被预约，下架
					_goods.setState(3);
				}
				// 设置商品预约数量
				_goods.setReservedCount(reservedCount + cartCount);
				// 添加商品
				goodsList.add(_goods);
			}
			// 设置订单
			Orders orders = new Orders();
			// 设置订单总额
			orders.setDbTotal(dbTotal);
			// 设置订单状态
			orders.setState(0);
			// 设置订单生成时间
			orders.setTime(new Date());
			// 设置订单所属用户
			User user =  new User();
			user.setUid(((User)session.getAttribute(Info.USER_SESSION)).getUid());
			orders.setUser(user);
			// 添加订单
			orderService.addOrder(orders, orderItemList, cartList, goodsList);
			// 添加聊天
			addChatByOrder(orderItemList, user.getUid(), notMeList);
			// 在session中保存一段uuid，用于用户再次查看预约成功页面
			String uuid = CommonUtils.uuid();
			session.setAttribute(Info.USER_APPOINTMENT, uuid);
			return new CommonResult<>(ResponseCode.SUCCESS, "success", uuid);
		} catch (Exception e) {
			return new CommonResult<>(ResponseCode.GOODS_NOT_FOUND);
		}
	}
	
	/**
	 * 	添加订单
	 * 
	 * */
	@ResponseBody
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public Object add(@RequestParam("id") String gid, 
			@RequestParam("count") String count,
			HttpServletRequest request, 
			HttpSession session,
			HttpServletResponse response) {
		// 处理session和Cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if (i == 0) {
			return new CommonResult<>(ResponseCode.UNLOGIN);
		}
		// 判断用户个人信息是否完整
		User userSession = (User)session.getAttribute(Info.USER_SESSION);
		if("".equals(userSession.getNickname()) || 
				"".equals(userSession.getPhoneNumber()) || "".equals(userSession.getDepartment())) {
			return new CommonResult<>(ResponseCode.INCOMPLETE_USER_INFO);
		}
		Integer gidInteger = null;
		Integer countInteger = null;
		try {
			gidInteger = Integer.parseInt(gid);
			countInteger = Integer.parseInt(count);
			List<Cart> cartList = new ArrayList<>();
			List<Goods> goodsList = new ArrayList<>();
			List<OrderItem> orderItemList = new ArrayList<>();
			List<Integer> notMeList = new ArrayList<>();
			
			// 根据gid查找Goods，查看有没有下架
			Goods _goods = new Goods();
			_goods.setState(1);
			_goods.setGid(gidInteger);
			Goods newGoods = goodsService.findGoods(_goods);
			if (newGoods == null) {
				throw new Exception();
			}
			// 不能预约自己发布的商品
			if(newGoods.getUser().getUid() == ((User)session.getAttribute(Info.USER_SESSION)).getUid()) {
				return new CommonResult<>(ResponseCode.ORDER_OWN_GOODS);
			}
			notMeList.add(newGoods.getUser().getUid());
			// 校验count
			int goodsCount = newGoods.getCount();
			int goodsReservedCount = newGoods.getReservedCount();
			if(countInteger > (goodsCount - goodsReservedCount) || (countInteger < 1)) {
				return new Exception();
			}
			// 商品预约数增加
			if(goodsReservedCount + countInteger > newGoods.getCount()) {
				throw new Exception();
			}
			if(goodsReservedCount + countInteger == newGoods.getCount()) {
				// 商品已全部被预约，下架
				_goods.setState(3);
			}
			// 设置商品预约数量
			_goods.setReservedCount(goodsReservedCount + countInteger);
			// 添加商品
			goodsList.add(_goods);
			// 查找Cart，若能找到则删除购物车项
			Cart _cart = new Cart();
			// 设置uid
			_cart.setUid(((User)session.getAttribute(Info.USER_SESSION)).getUid());
			// 设置gid
			Goods goods = new Goods();
			goods.setGid(gidInteger);
			_cart.setGoods(goods);
			// 设置未删除
			_cart.setIsDel(0);
			List<Cart> _cartList = cartService.findCartAll(_cart);
			if(_cartList != null) {
				// 设置删除
				_cart.setIsDel(1);
				// 设置cartId
				_cart.setCartId(_cartList.get(0).getCartId());
				cartList.add(_cart);
			}
			// 设置订单子项
			OrderItem orderItem = new OrderItem();
			// 设置购买的商品数量
			orderItem.setCount(countInteger);
			// 设置订单小计
			orderItem.setDbSubtotal(newGoods.getDbPrice() * countInteger);
			// 设置订单子项对应的商品
			orderItem.setGoods(goods);
			// 设置订单子项状态
			orderItem.setState(0);
			// 订单子项未设置oid
			orderItemList.add(orderItem);
			// 设置订单
			Orders orders = new Orders();
			// 设置订单总额
			orders.setDbTotal(orderItem.getDbSubtotal());
			// 设置订单状态
			orders.setState(0);
			// 设置订单生成时间
			orders.setTime(new Date());
			// 设置订单所属用户
			User user =  new User();
			user.setUid(((User)session.getAttribute(Info.USER_SESSION)).getUid());
			orders.setUser(user);
			// 添加订单
			orderService.addOrder(orders, orderItemList, cartList, goodsList);
			// 添加聊天
			addChatByOrder(orderItemList, user.getUid(), notMeList);
			// 在session中保存一段uuid，用于用户再次查看预约成功页面
			String uuid = CommonUtils.uuid();
			session.setAttribute(Info.USER_APPOINTMENT, uuid);
			return new CommonResult<>(ResponseCode.SUCCESS, "success", uuid);
		}catch(Exception e) {
			return new CommonResult<>(ResponseCode.GOODS_NOT_FOUND);
		}
	}
	
	/**
	 * 	获取session中保存的uuid
	 * 
	 * */
	@ResponseBody
	@RequestMapping(value = "/aptId", method = RequestMethod.POST)
	public Object aptId(@RequestParam("id") String aptId,
			HttpSession session) {
		if(aptId.equals((String)session.getAttribute(Info.USER_APPOINTMENT))) {
			return new CommonResult<>(ResponseCode.SUCCESS);
		} else {
			return new CommonResult<>(ResponseCode.INCORECT_FORMAT);
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	@Resource
	private ChatService chatService;
	
	/**
	 *	 从订单中添加聊天记录,供OrderController调用
	 *	orderItemList：订单子项
	 *	me：下订单的用户
	 *	notMe：商品卖家
	 * */
	public void addChatByOrder(List<OrderItem> orderItemList, Integer me, List<Integer> notMeList) {
		List<ChatItem> chatItemList = new ArrayList<>();
		List<Chat> chatList = new ArrayList<>();
		for(int i = 0; i < orderItemList.size(); i++) {
			OrderItem orderItem = orderItemList.get(i);
			// 设置聊天子项
			ChatItem chatItem = new ChatItem();
			// 未删除
			chatItem.setIsDel(0);
			// 订单子项
			chatItem.setOrderItem(orderItem);
			// 发送方
			chatItem.setSendId(me);
			// 接收方
			chatItem.setReceivedId(notMeList.get(i));
			// 时间
			chatItem.setTime(new Date());
			// 没有设置聊天内容和uuid
			// 设置聊天
			Chat chat = new Chat();
			// 下订单的用户
			User userMy = new User();
			userMy.setUid(me);
			chat.setMe(userMy);
			// 商品卖家
			User userOthers = new User();
			userOthers.setUid(notMeList.get(i));
			chat.setNotMe(userOthers);
			chatList.add(chat);
			chatItemList.add(chatItem);
		}
		chatService.addChatByOrder(chatList, chatItemList);
	}

}
